import jwt
from django.http import JsonResponse
from django.shortcuts import render, HttpResponse, redirect
from django import http
from django.contrib.sessions.models import Session
from functools import wraps
from Administrative_office_system import settings
from personal_center.models import User, BillGroup


def my_decorator(view):
    '''自定义的装饰器:判断是否登录'''
    def wrapper(request, *args, **kwargs):
        try:
            x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')  # 判断是否使用代理
            if x_forwarded_for:
                ip = x_forwarded_for.split(',')[0]  # 使用代理获取真实的ip
            else:
                ip = request.META.get('REMOTE_ADDR')  # 未使用代理获取IP
            print('IP:', ip, '\n')
        except:
            print('获取请求IP失败！')

        if request.user.is_authenticated:
            # 如果用户登录, 则进入这里,正常执行
            return view(request, *args, **kwargs)
        else:
            # try:
            token = request.GET.get('token')

            if not token:
                token = request.POST.get('token')
                if not token:
                    return redirect("/personal-center/signin")
            try:
                print('token===========', token)
                token_dict = jwt.decode(token, settings.SECRET_KEY, algorithms=['HS256'])
                print("token_dict: ", token_dict)
                username = token_dict.get('username')
            except jwt.ExpiredSignatureError:
                return JsonResponse({"status_code": 401, "message": "Token expired"})
            except jwt.InvalidTokenError:
                return JsonResponse({"status_code": 401, "message": "Invalid token"})
            except Exception as e:
                return JsonResponse({"status_code": 401, "message": "Can not get user object"})
            try:
                print("username: ", username)
                user = User.objects.get(username=username)
            except User.DoesNotExist:
                return JsonResponse({"status_code": 401, "message": "User Does not exist"})
            request.user = user
            return view(request, *args, **kwargs)
            # except Exception as e:
            #     print('未登录:',e)
            #     # 如果用户未登录,则进入这里,返回400的状态码
            #     return redirect("/personal-center/signin")
    return wrapper




class LoginRequiredMixin(object):
    '''自定义的Mixin扩展类'''

    # 重写的 as_view 方法
    @classmethod
    def as_view(cls, **initkwargs):
        view = super().as_view(**initkwargs)
        # view = super(LoginRequiredMixin, cls).as_view(**initkwargs)
        # 调用上面的装饰器进行过滤处理:
        return my_decorator(view)


def GetGroupView(menu, user):
    bill_groups = BillGroup.objects.filter(menu=menu, type='pc')
    dic = {}
    print(user.job_number)
    if len(bill_groups) == 0:
        dic['code'] = '0'
        dic['mesg'] = '未找到菜单为[%s]的权限配置，请联系管理员检查！' % menu
        return dic
    for bill_group in bill_groups:
        dic[bill_group.bill] = False
        if bill_group.apply_user and user.job_number in [i.strip() for i in bill_group.apply_user.split(', ')]:
            dic[bill_group.bill] = True
        for group in bill_group.groups.all():
            # print(group.user_set.all())
            if user in group.user_set.all():
                dic[bill_group.bill] = True
    return dic
